//个人中心
var ObjectId=require('mongodb').ObjectId;
var router =require('express').Router();
var async=require('async');
var moment=require('moment');
var History=require('../model/history');
var Favorite=require('../model/favorite');
var Book=require('../model/book');

module.exports = router;
router.get('/',(req, res)=>{
    if(!req.session.user)return res.redirect('/');
    res.render('ucenter',{
        title:'个人中心',
        user:req.session.user
    });
});

//浏览记录
router.get('/history',(req, res,next)=>{
    if(!req.session.user ||!req.session.user._id)return res.redirect('/');

    History.find({user:req.session.user._id},{_id:true,book:true,date:true,userName:true},{sort:{date:-1}},(err,docs)=>{
        if(err)return next(err);

        var history=[];
        for(var doc of docs){
            var idx=history.findIndex((item)=>{return item.date==doc.date});
            if(~idx){
                history[idx].ids.push(doc.book);
            }else{
                history.push({
                    date:doc.date,
                    ids:[doc.book]
                });
            }
        };
        var ret=[];
        async.each(history,(item,cb)=>{
            Book.find({_id:{$in:item.ids}},{sku:true,name:true,img:true,price:true,market:true},(err,books)=>{
                if(err)return next(err);
                ret.push({
                    date:item.date,
                    books:books
                });
                cb();
            });
        },(err)=>{
            if(err)return next(err);
            ret.sort((a,b)=>{return new Date(a.date).getTime()>new Date(b.date).getTime()?-1:1});

            //重排为history的顺序
            var today=moment(new Date()).format('YYYY-MM-DD');
            var yesterday=moment(new Date()-1000*3600*24).format('YYYY-MM-DD');

            for(var his of history){
                for(var r of ret){

                    if(r.date==today)r.day='今天';
                    if(r.date==yesterday)r.day='昨天';

                    if(r.date==his.date){
                        var books=[];
                        for(var id of his.ids){
                            for(var book of r.books){
                                if(book._id.toString()==id.toString()){
                                    books.push(book);
                                    break;
                                }
                            }
                        }
                        r.books=books;
                        break;
                    }
                }
            }
            res.render('history',{
                title:'浏览历史',
                user:req.session.user,
                history:ret
            });
        });
    });
});
router.delete('/history',(req,res,next)=>{
    if(!req.session.user || !req.session.user._id)return res.redirect('/');
    var body=req.body,query={user:ObjectId(body.user_id)};
    if(body.book_id){
        query.book=ObjectId(body.book_id);
    }else if(body.date){
        query.date=body.date;
    }

    if(query){
        History.remove(query,(err,ret)=>{
            if(err)return res.json({error:'INTERNAL SERVER ERROR',code:500});
            res.json({success:true,code:200});
        });
    }else{
        res.json({error:'Not Acceptable',code:406});
    }

});


//商品收藏
router.get('/favorite',(req,res,next)=>{
    if(!req.session.user || !req.session.user._id)return res.redirect('/');
    Favorite.find({user_id:req.session.user._id},{_id:false,sku:true},{sort:{time:-1}},(err,skus)=>{
        if(err)return next(err);
        skus=skus.map((sku)=>{return sku.sku});

        Book.page({sku:{$in:skus}},{},{},(err,books)=>{
            if(err)return next(err);

            var ret=[];
            for(var sku of skus){
                for(var book of books){
                    if(sku==book.sku){
                        ret.push(book);
                        break;
                    }
                }
            }

            res.render('favorite',{
                title:'商品收藏',
                user:req.session.user,
                books:ret
            });

        });
    });
});
//--添加
router.post('/favorite',(req,res,next)=>{
    if(!req.session.user || !req.session.user._id)return res.redirect('/');
    //console.log('post body:',req.body);
    Favorite.update({
        user_id:ObjectId(req.session.user._id),
        userName:req.body.userName,
        sku:req.body.sku,
        bookTitle:req.body.bookTitle
    },{time:new Date()},{upsert:true},(err,ret)=>{
        res.json({error:err||null,success:ret?true:false});
    });
});

router.delete('/favorite',(req,res,next)=>{
    if(!req.session.user || !req.session.user._id)return res.redirect('/');

    //console.log('del favorite body:',req.body);
    var body=req.body,query;
    if(body.sku){//删除单个
        query={user_id:ObjectId(body.user_id),sku:body.sku};
    }else if(body.skus){//批量删除
        query={user_id:ObjectId(body.user_id),sku:{$in:body.skus}};
    }

    if(query){
        Favorite.remove(query,(err,ret)=>{
            if(err)return res.json({error:'INTERNAL SERVER ERROR',code:500});
            res.json({success:true,code:200});
        });
    }else{
        res.json({error:'Not Acceptable',code:406});
    }

});